/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package manage;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.*;
import java.util.*;
import javax.microedition.io.file.*;
import javax.microedition.io.*;
   



/**
 * @author raghul
 */
public class MoneyMIDlet extends MIDlet implements CommandListener {

    private boolean midletPaused = false;
    Filter filter;
      private RecordEnumeration recordEnumeration = null;

//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
private Command exitCommand;
private Command okCommand;
private Command okCommand1;
private Command okCommand2;
private Form form;
private TextField textField1;
private ChoiceGroup choiceGroup;
private TextField textField;
private Spacer spacer;
//</editor-fold>//GEN-END:|fields|0|
private String [] description;
private Float [] amount;
private Vector ExpData;
private String ExpDataString;
	RecordStore rs = null;
        MoneyMIDlet mm;
          Calendar myCalender ;
          String Date;
    /**
     * The HelloMIDlet constructor.
     */
    public MoneyMIDlet() {
          mm = this;
        
            myCalender =  Calendar.getInstance (TimeZone.getTimeZone("GMT+05:30"));
           
                Date = getUniversalDateStamp(myCalender);
       
    }

//<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
//</editor-fold>//GEN-END:|methods|0|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
/**
 * Initilizes the application.
 * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
 */
private void initialize () {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    try{
    rs = RecordStore.openRecordStore("ManageMoney", true);
          NameFilter nameFilter = new NameFilter(Date);
      NameComparator nameComparator = new NameComparator();
      searchAndDisplayRecords(nameFilter,nameComparator);
    }catch(Exception e){
        System.out.println("error in oprn rms"+e);
    }
    ExpData = new Vector();
}//GEN-BEGIN:|0-initialize|2|
//</editor-fold>//GEN-END:|0-initialize|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
/**
 * Performs an action assigned to the Mobile Device - MIDlet Started point.
 */
public void startMIDlet () {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
switchDisplayable (null, getForm ());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
}//GEN-BEGIN:|3-startMIDlet|2|
//</editor-fold>//GEN-END:|3-startMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
/**
 * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
 */
public void resumeMIDlet () {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
}//GEN-BEGIN:|4-resumeMIDlet|2|
//</editor-fold>//GEN-END:|4-resumeMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
/**
 * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
 * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
 * @param nextDisplayable the Displayable to be set
 */
public void switchDisplayable (Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
Display display = getDisplay ();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
if (alert == null) {
display.setCurrent (nextDisplayable);
} else {
display.setCurrent (alert, nextDisplayable);
}//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
}//GEN-BEGIN:|5-switchDisplayable|2|
//</editor-fold>//GEN-END:|5-switchDisplayable|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
/**
 * Called by a system to indicated that a command has been invoked on a particular displayable.
 * @param command the Command that was invoked
 * @param displayable the Displayable where the command was invoked
 */
public void commandAction (Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
if (displayable == form) {//GEN-BEGIN:|7-commandAction|1|19-preAction
if (command == exitCommand) {//GEN-END:|7-commandAction|1|19-preAction
                // write pre-action user code here
exitMIDlet ();//GEN-LINE:|7-commandAction|2|19-postAction
                // write post-action user code here
} else if (command == okCommand) {//GEN-LINE:|7-commandAction|3|24-preAction
 // write pre-action user code here
//GEN-LINE:|7-commandAction|4|24-postAction
 // write post-action user code here
    if(!textField.getString().equals("") && !textField1.getString().equals("")){
    putDataToRMS();
    textField.setString("");
    textField1.setString("");
    new Thread(){
        public void run(){
          Alert myAlert = new Alert("Info");
        String alertString =  " Data Saved" ;
       myAlert.setString(alertString);
       myAlert.setTimeout(1000);
           mm.getDisplay().setCurrent(myAlert);
        }
    }.start();
    }
    else{
        
          new Thread(){
        public void run(){
          Alert myAlert = new Alert("Error");
          
        String alertString =  " Enter the data correctly " ;
        myAlert.setType(AlertType.ERROR);
       myAlert.setString(alertString);
       myAlert.setTimeout(1000);
           mm.getDisplay().setCurrent(myAlert);
        }
    }.start();
        
    }
} else if (command == okCommand1) {//GEN-LINE:|7-commandAction|5|30-preAction
 // write pre-action user code here
//GEN-LINE:|7-commandAction|6|30-postAction
 // write post-action user code here
    exportToXL();
} else if (command == okCommand2) {//GEN-LINE:|7-commandAction|7|33-preAction
 // write pre-action user code here
//GEN-LINE:|7-commandAction|8|33-postAction
 // write post-action user code here
    show_total();
}//GEN-BEGIN:|7-commandAction|9|7-postCommandAction
}//GEN-END:|7-commandAction|9|7-postCommandAction
        // write post-action user code here
}//GEN-BEGIN:|7-commandAction|10|
//</editor-fold>//GEN-END:|7-commandAction|10|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|18-getter|0|18-preInit
/**
 * Returns an initiliazed instance of exitCommand component.
 * @return the initialized component instance
 */
public Command getExitCommand () {
if (exitCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
exitCommand = new Command ("Exit", Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
}//GEN-BEGIN:|18-getter|2|
return exitCommand;
}
//</editor-fold>//GEN-END:|18-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">//GEN-BEGIN:|14-getter|0|14-preInit
/**
 * Returns an initiliazed instance of form component.
 * @return the initialized component instance
 */
public Form getForm () {
if (form == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
form = new Form ("Manage Money", new Item[] { getChoiceGroup (), getSpacer (), getTextField (), getTextField1 () });//GEN-BEGIN:|14-getter|1|14-postInit
form.addCommand (getExitCommand ());
form.addCommand (getOkCommand ());
form.addCommand (getOkCommand1 ());
form.addCommand (getOkCommand2 ());
form.setCommandListener (this);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
}//GEN-BEGIN:|14-getter|2|
return form;
}
//</editor-fold>//GEN-END:|14-getter|2|





//<editor-fold defaultstate="collapsed" desc=" Generated Getter: textField1 ">//GEN-BEGIN:|22-getter|0|22-preInit
/**
 * Returns an initiliazed instance of textField1 component.
 * @return the initialized component instance
 */
public TextField getTextField1 () {
if (textField1 == null) {//GEN-END:|22-getter|0|22-preInit
 // write pre-init user code here
textField1 = new TextField ("Amount", null, 32, TextField.NUMERIC);//GEN-LINE:|22-getter|1|22-postInit
 // write post-init user code here
}//GEN-BEGIN:|22-getter|2|
return textField1;
}
//</editor-fold>//GEN-END:|22-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand ">//GEN-BEGIN:|23-getter|0|23-preInit
/**
 * Returns an initiliazed instance of okCommand component.
 * @return the initialized component instance
 */
public Command getOkCommand () {
if (okCommand == null) {//GEN-END:|23-getter|0|23-preInit
 // write pre-init user code here
okCommand = new Command ("Save", Command.OK, 0);//GEN-LINE:|23-getter|1|23-postInit
 // write post-init user code here
}//GEN-BEGIN:|23-getter|2|
return okCommand;
}
//</editor-fold>//GEN-END:|23-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: choiceGroup ">//GEN-BEGIN:|26-getter|0|26-preInit
/**
 * Returns an initiliazed instance of choiceGroup component.
 * @return the initialized component instance
 */
public ChoiceGroup getChoiceGroup () {
if (choiceGroup == null) {//GEN-END:|26-getter|0|26-preInit
 // write pre-init user code here
choiceGroup = new ChoiceGroup ("", Choice.POPUP);//GEN-BEGIN:|26-getter|1|26-postInit
choiceGroup.setFitPolicy (Choice.TEXT_WRAP_DEFAULT);
choiceGroup.setSelectedFlags (new boolean[] {  });//GEN-END:|26-getter|1|26-postInit
 // write post-init user code here
}//GEN-BEGIN:|26-getter|2|
return choiceGroup;
}
//</editor-fold>//GEN-END:|26-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: textField ">//GEN-BEGIN:|28-getter|0|28-preInit
/**
 * Returns an initiliazed instance of textField component.
 * @return the initialized component instance
 */
public TextField getTextField () {
if (textField == null) {//GEN-END:|28-getter|0|28-preInit
 // write pre-init user code here
textField = new TextField ("Details", "", 32, TextField.ANY | TextField.INITIAL_CAPS_WORD);//GEN-BEGIN:|28-getter|1|28-postInit
textField.setLayout (ImageItem.LAYOUT_DEFAULT);//GEN-END:|28-getter|1|28-postInit
 // write post-init user code here
}//GEN-BEGIN:|28-getter|2|
return textField;
}
//</editor-fold>//GEN-END:|28-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand1 ">//GEN-BEGIN:|29-getter|0|29-preInit
/**
 * Returns an initiliazed instance of okCommand1 component.
 * @return the initialized component instance
 */
public Command getOkCommand1 () {
if (okCommand1 == null) {//GEN-END:|29-getter|0|29-preInit
 // write pre-init user code here
okCommand1 = new Command ("Export to xl", Command.OK, 0);//GEN-LINE:|29-getter|1|29-postInit
 // write post-init user code here
}//GEN-BEGIN:|29-getter|2|
return okCommand1;
}
//</editor-fold>//GEN-END:|29-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: spacer ">//GEN-BEGIN:|31-getter|0|31-preInit
/**
 * Returns an initiliazed instance of spacer component.
 * @return the initialized component instance
 */
public Spacer getSpacer () {
if (spacer == null) {//GEN-END:|31-getter|0|31-preInit
 // write pre-init user code here
spacer = new Spacer (16, 1);//GEN-LINE:|31-getter|1|31-postInit
 // write post-init user code here
}//GEN-BEGIN:|31-getter|2|
return spacer;
}
//</editor-fold>//GEN-END:|31-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand2 ">//GEN-BEGIN:|32-getter|0|32-preInit
/**
 * Returns an initiliazed instance of okCommand2 component.
 * @return the initialized component instance
 */
public Command getOkCommand2 () {
if (okCommand2 == null) {//GEN-END:|32-getter|0|32-preInit
 // write pre-init user code here
okCommand2 = new Command ("show total", Command.OK, 0);//GEN-LINE:|32-getter|1|32-postInit
 // write post-init user code here
}//GEN-BEGIN:|32-getter|2|
return okCommand2;
}
//</editor-fold>//GEN-END:|32-getter|2|



    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }
 public void putDataToRMS(){
     
     		//RecordStore rs = null;
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		DataOutputStream dout = new DataOutputStream(bout);

		try {
                     byte[] outputRecord;
                     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                     DataOutputStream outputDataStream =    new DataOutputStream(outputStream);
                    outputDataStream.writeUTF(textField.getString() );
                     outputDataStream.writeFloat(Float.parseFloat(textField1.getString()));
                   
               
                       String Time =  convertToTimeStamp(myCalender,true);
                   System.out.println(Time);
                 
                     outputDataStream.writeUTF(Time); 
                     outputDataStream.writeUTF(Date); 
                    outputDataStream.flush();               
                 outputRecord = outputStream.toByteArray();
                     rs.addRecord(outputRecord, 0, outputRecord.length);
                    outputStream.reset();   
                  outputStream.close();
                      outputDataStream.close();
                    
                    
                        
		} catch(Exception e){
                System.out.println("EXce" +e);
                }
                        
                        finally {
			try {
				dout.close();
			} catch (Exception e) {
			}

			if (rs != null) {
				try {
					//rs.closeRecordStore();
				} catch (Exception e) {
				}
			}
		}
     
 }
 
 public void exportToXL(){
     
//FileChooser ff= new FileChooser();
//this.switchDisplayable(null, ff);
     
         new Thread(){
             public void run(){
                   try{   
                       
                       
                       
                      
                      FileConnection filecon = (FileConnection) Connector.open("file:///E:/expense.xls", Connector.READ_WRITE);

                             if ( ! filecon.exists()) {
                filecon.create();
        }
       OutputStream out = filecon.openOutputStream();
        PrintStream output = new PrintStream( out );
        
   
       
         
         
        byte[] byteInputData = new byte[100]; 
        ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
       DataInputStream inputDataStream = new DataInputStream(inputStream);
        for (int x = 1; x <= rs.getNumRecords(); x++)
        { 
         rs.getRecord(x, byteInputData, 0);
         ExpDataString = inputDataStream.readUTF();
         ExpDataString =ExpDataString +"\t"+ inputDataStream.readFloat();
         ExpDataString =ExpDataString +"\t"+inputDataStream.readUTF();
         ExpDataString =ExpDataString +"\t"+inputDataStream.readUTF();
        System.out.println( ExpDataString);
         output.println(ExpDataString );
         inputStream.reset();
        }
        inputStream.close();
        inputDataStream.close();
       out.close();
       filecon.close();   
     }catch(Exception e){
         System.out.println("Wheile reading "+e);
     }
                 
             }
         }.start();
   
        new Thread(){
        public void run(){
          Alert myAlert = new Alert("Info");
        String alertString =  "Exported to excel file to E:/" ;
       myAlert.setString(alertString);
       myAlert.setTimeout(1000);
           mm.getDisplay().setCurrent(myAlert);
        }
    }.start();
 }
 
 
     public static String convertToTimeStamp(Calendar time, boolean showSeconds) {
        String hours = Integer.toString(time.get(Calendar.HOUR_OF_DAY));
        if (hours.length() == 1) {
            hours = '0' + hours;
        }
        String minutes = Integer.toString(time.get(Calendar.MINUTE));
        if (minutes.length() == 1) {
            minutes = '0' + minutes;
        }
        if (showSeconds) {
            String seconds = Integer.toString(time.get(Calendar.SECOND));
            if (seconds.length() == 1) {
                seconds = '0' + seconds;
            }
            System.out.println(hours + ":" + minutes + ":" + seconds);
            return hours + ":" + minutes + ":" + seconds;
        } else {
            return hours + ":" + minutes;
        }
    }
     
      public static String getUniversalDateStamp(Calendar cal) {
        String year = String.valueOf(cal.get(Calendar.YEAR));
        String month = String.valueOf(cal.get(Calendar.MONTH) + 1);
        if (month.length() == 1) {
            month = "0" + month;
        }
        String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
        if (day.length() == 1) {
            day = "0" + day;
        }
         String dateStamp = day + "/" + month + "/" + year ;
        return dateStamp;
      }
      
      class Filter implements RecordFilter
{
  private String search = null;
  private ByteArrayInputStream inputstream = null;
  private DataInputStream datainputstream = null;
  public Filter(String search)
  {
    this.search = search;//.toLowerCase();
    System.out.println("Search string " +search);
  }
  public boolean matches(byte[] suspect)
  {
    String string = new String(suspect);//.toLowerCase();
    if (string!= null && string.indexOf(search) != -1)
      return true;
    else
      return false;
  }
  public void filterClose()
  {
    try
    {
      if (inputstream != null)
      {
        inputstream.close();
      }
      if (datainputstream != null)
      {
        datainputstream.close();
      }
    }
    catch ( Exception error)
    {
    }
  }
}

 void show_total(){
                try
      {
        filter = new Filter("tea");
        recordEnumeration = rs.enumerateRecords(
                     filter, null, false);
        System.out.println(recordEnumeration.numRecords());
        if (recordEnumeration.numRecords() > 0)
        {
          String string = new String(recordEnumeration.nextRecord());
           System.out.println(string);
        }
      }
      catch (Exception error)
      {
     System.out.println("Error"+error);
      }
                
           }
       class NameFilter implements RecordFilter {

String name;

public NameFilter(String filterOnThisName) {
  name = filterOnThisName;
}

public boolean matches(byte [] candidateRecord) {
  try{
    ByteArrayInputStream bais = new ByteArrayInputStream(candidateRecord);
    DataInputStream dis = new DataInputStream(bais);
    String nameFromRec1 = dis.readUTF();
    float ff =  dis.readFloat();
    String nameFromRec2 = dis.readUTF();
    String  nameFromRec = dis.readUTF();
     System.out.println (" nameFromRec "+nameFromRec);
    dis.close();
    bais.close();
    if (name.compareTo(nameFromRec) == 0 )
      return true;
    }
  catch (Exception e) {
    System.out.print("Error in NameFilter.matches -> ");
    System.out.println("Exception : " + e.getMessage());
  }
  return false;
}

}


class NameComparator implements RecordComparator {

public int compare(byte [] rec1, byte [] rec2) {
  try{
    // read first record and extract name
    ByteArrayInputStream bais1 = new ByteArrayInputStream(rec1);
    DataInputStream dis1 = new DataInputStream(bais1);
    String name222 = dis1.readUTF();
  
    float ff =  dis1.readFloat();
    String name22 = dis1.readUTF();
    String  name1 = dis1.readUTF();
   // System.out.println(name1);
    dis1.close();
    bais1.close();

    // read second record and extract name
    ByteArrayInputStream bais2 = new ByteArrayInputStream(rec2);
    DataInputStream dis2 = new DataInputStream(bais2);
    String name22222 = dis2.readUTF();
       float f2f =  dis2.readFloat();
    String name2222 = dis2.readUTF();
    String  name2 = dis2.readUTF();
    dis2.close();
    bais2.close();

    if (name1.compareTo(name2) < 0 )
      return PRECEDES;
    if (name1.compareTo(name2) > 0 )
      return FOLLOWS;
  }
  catch (Exception e) {
    System.out.print("Error in NameComparator.compare -> ");
    System.out.println("Exception : " + e.getMessage());
  }
  return EQUIVALENT;
}
}

  public void searchAndDisplayRecords(NameFilter f, NameComparator c){
        float total=0;
    try {
        RecordEnumeration rEnum = rs.enumerateRecords( f, c , false);
        System.out.println("Total Records in Enumeration: " + rEnum.numRecords());
        while (rEnum.hasNextElement()){
          byte [] bRec = rEnum.nextRecord();
          ByteArrayInputStream bais = new ByteArrayInputStream(bRec);
          DataInputStream dis = new DataInputStream(bais);
          String name = dis.readUTF();
          float bDay = dis.readFloat();
          total = total + bDay;
          System.out.println("Details: " + name + " Rate: "+ bDay);
        }
               System.out.println("Total "+ total);
      }
      catch (Exception e) {
        System.out.print("Error in BirthdayDB.searchAndDisplayRecords -> ");
        System.out.println("Exception : " + e.getMessage());
      }
      return;
  }
}
